package com.fary.security.config.annotation.configuration;

import com.fary.beans.factory.DisposableBean;
import com.fary.beans.factory.SmartInitializingSingleton;
import com.fary.beans.factory.config.AutowireCapableBeanFactory;
import com.fary.security.config.annotation.ObjectPostProcessor;
import com.fary.util.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.List;

final class AutowireBeanFactoryObjectPostProcessor implements ObjectPostProcessor<Object>, DisposableBean, SmartInitializingSingleton {
    private final Log logger = LogFactory.getLog(getClass());
    private final AutowireCapableBeanFactory autowireBeanFactory;
    private final List<DisposableBean> disposableBeans = new ArrayList<>();
    private final List<SmartInitializingSingleton> smartSingletons = new ArrayList<>();

    AutowireBeanFactoryObjectPostProcessor(AutowireCapableBeanFactory autowireBeanFactory) {
        Assert.notNull(autowireBeanFactory, "autowireBeanFactory cannot be null");
        this.autowireBeanFactory = autowireBeanFactory;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.springframework.security.config.annotation.web.Initializer#initialize(java.
     * lang.Object)
     */
    @SuppressWarnings("unchecked")
    /**
     * // 对某个刚刚创建的对象 object 执行这里所谓的 post-process 流程 :
     * 1. 使用指定的 autowireBeanFactory 对该对象 object 执行初始化过程;
     * 2. 使用指定的 autowireBeanFactory 对该对象 object 执行依赖注入过程;
     * 3. 如果该对象 object 是一个 DisposableBean , 则将它记录下来，在当前对象的destroy()
     *    被调用时，它们的 destroy() 方法也都会被调用;
     * 4. 如果该对象 object 是一个 SmartInitializingSingleton , 则将它记录下来，
     *    在当前对象的 afterSingletonsInstantiated () 被调用时，它们的 afterSingletonsInstantiated()
     *    方法也都会被调用;
     */
    public <T> T postProcess(T object) {
        if (object == null) {
            return null;
        }
        T result = null;
        try {
            result = (T) this.autowireBeanFactory.initializeBean(object, object.toString());
        } catch (RuntimeException e) {
            Class<?> type = object.getClass();
            throw new RuntimeException("Could not postProcess " + object + " of type " + type, e);
        }
        this.autowireBeanFactory.autowireBean(object);
        if (result instanceof DisposableBean) {
            this.disposableBeans.add((DisposableBean) result);
        }
        if (result instanceof SmartInitializingSingleton) {
            this.smartSingletons.add((SmartInitializingSingleton) result);
        }
        return result;
    }

    @Override
    public void afterSingletonsInstantiated() {
        for (SmartInitializingSingleton singleton : smartSingletons) {
            singleton.afterSingletonsInstantiated();
        }
    }

    public void destroy() {
        for (DisposableBean disposable : this.disposableBeans) {
            try {
                disposable.destroy();
            } catch (Exception error) {
                this.logger.error(error);
            }
        }
    }

}